package core

import (
	"fmt"
	"sync/atomic"
	"time"
	"x1aCron/internal/global"
)


type Task struct {
	ID       int64
	Interval time.Duration
	Next     time.Time
	ToDo     func()
}

func NewTask(interval time.Duration, todo func()) *Task {
	task := &Task{
		ID:       atomic.AddInt64(&global.TaskID, 1),
		Interval: interval,
		Next:     time.Now().Add(interval),
		ToDo:     todo,
	}
	return task
}

func NewTaskWithSelf(interval time.Duration, todo func(t *Task)) *Task {
	task := &Task{
		ID:       atomic.AddInt64(&global.TaskID, 1),
		Interval: interval,
		Next:     time.Now().Add(interval),
	}
	task.ToDo = func() {
		todo(task)
	}
	return task
}

func (t *Task) Run() {
	fmt.Println("Task ID:", t.ID, "is running at", time.Now())
	go t.ToDo()
	t.Next = time.Now().Add(t.Interval)
}
